<!--
 * @Author: your name
 * @Date: 2020-04-17 17:02:39
 * @LastEditTime: 2020-06-18 11:02:33
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \v-nw-h5\src\components\wx\WxShareBody.vue
 -->
<template>
    <div>
        <wx-show-menu></wx-show-menu>
        <wx_share_pub_qrcode v-if="shareBody && shareBody.wxPubQrcode" :wxPubQrcode="shareBody.wxPubQrcode">
        </wx_share_pub_qrcode>
    </div>
</template>
<script>
import WxSharePubQrcode from './WxSharePubQrcode'

let wx = require('weixin-js-sdk');
import ts from '../../../static/js/trace-share'
import Session from '../../../static/js/Session'
import xurl from '../../x/xurl'
import { mapState } from 'vuex'
import StringUtils from '../../utils/StringUtils'
import XWxConfig from '../../x/XWxConfig'

export default {
    data () {
        return {
            giveChannel: '0',
            identityType: 0,
            identityKey: 0,
            browseType: Session.get('browseType'),
            browseId: Session.get('browseId'),
            browseIsLog: Session.get('browseIsLog'),
            shareUrlKey: Session.get('shareUrlKey'),
            defaultShareBody: {
                shareType: 0,
                title: "您的好友邀请您一起参加活动",
                photo: this.staticImageUrl('images/index/nvWa_logo.png'),
                content: '您的好友邀请您一起参加活动',
                link: window.location.href
            },
        }
    },
    props: {
        shareBody: {
            type: Object
        },
        storeId: {
            type: String
        },

    },
    created () {

        // this.init(shareBody);
    },
    mounted () {
        if(this.v_is_weixin){
            let shareBody = this.shareBody ? this.shareBody : this.defaultShareBody;
            this.init(shareBody);
        }
    },
    computed: {
        ...mapState({
            wxData:state=>state.api.wxData,
            mediaId:state=>state.logic.mediaId,
        }),
    },
    methods: {
        // ...mapMutations(['createNeplayerRoom','sendGroupMsg','getChatRoomAddress','playChannelApi','leaveChatRoom','discountRoom','shareShow']),
        async init (shareBody) {
            let that = this;

            // let params = {
            //     shareType:this.$route.query.menuType,
            //     shareId:this.mediaId,
            //     storeId:this.$route.query.storeId,
            //     userId:this.userId+'',
            //     menuId:this.$route.query.menuId,
            //     sendShareMsg: sendShareMsg
            //     }
            this.identityKey = this.$store.state.shareInfo && this.$store.state.shareInfo.identityKey ? this.$store.state.shareInfo.identityKey : 0;
            this.identityType = this.$store.state.shareInfo && this.$store.state.shareInfo.identityType ? this.$store.state.shareInfo.identityType : 0;
            // console.log("browseType:" + this.browseType)
            // console.log("browseId:" + this.browseId)
            // console.log("browseIsLog:" + this.browseIsLog)
            // console.log("shareUrlKey:" + this.shareUrlKey)
            // console.log("shareBody:" + JSON.stringify(this.shareBody))
            ts.pgShare.config.browseType = this.browseType == null ? "" : this.browseType.toString()
            ts.pgShare.config.browseId = this.browseId == null ? "" : this.browseId.toString()
            ts.pgShare.config.browseIsLog = Boolean(this.browseIsLog);
            ts.pgShare.config.shareUrlKey = this.shareUrlKey//"<%=ResourceContants.TRACE_SHARE_ID%>";
            ts.pgShare.config.parentShareId = ts.pgShare.getQueryParam(ts.pgShare.config.shareUrlKey);
            ts.pgShare.config.channel = 1;     // 分享平台：微信

            let shareTitle = !!shareBody && !!shareBody.title ? shareBody.title.trim() : '';
            let sharePhoto = !!shareBody && !!shareBody.photo ? shareBody.photo.trim() : '';
            let shareSummary = !!shareBody && !!shareBody.content ? shareBody.content.trim() : '';
            let link = !!shareBody && !!shareBody.link ? shareBody.link.trim() : '';
            if (!link) {
                link = window.location.href;
                if (link.indexOf('identityKey') <= 0 && this.identityType != 0 && this.identityKey != 0) {
                    if (link.indexOf('?') > 0) {
                        link = link + "&identityType=" + this.identityType + "&identityKey=" + this.identityKey;
                    } else {
                        link = link + "?identityType=" + this.identityType + "&identityKey=" + this.identityKey;
                    }
                }
            }
            // console.log("identityType=" + this.identityType + "----" + "identityKey=" + this.identityKey + "link=" + link + "-shareTitle=" + shareTitle + "==sharePhoto==" + sharePhoto)
            $("#article_share_block").click(function () {
                $("#black_tk").hide();
            });
            let params = {
                shareType: this.$route.query && this.$route.query.menuType ? this.$route.query.menuType : 2,
                shareId: this.mediaId,
                storeId: this.$route.query && this.$route.query.storeId ? this.$route.query.storeId : this.storeId,
                userId: this.userId,
                menuId: this.$route.query.menuId,
                terminalType: '6',
                sendShareMsg: false
            }
            //获取微信分享信息
            if (window.location.pathname.indexOf('store') != -1) {
                if (params.shareType == '6') {
                    params.shareType = '10'
                }
                await this.$store.commit('getWxUserInfo', params)
            } else if (this.$route.query.page.indexOf('looking') != -1) {
                await this.$store.commit('getWxUserInfoHKHW', params)
            } else if (this.$route.query.page.indexOf('activity') != -1) {
                params.shareType = '6'
                params.menuId = '2'
                await this.$store.commit('getWxUserInfo', params)
            }
            let readyData = {}
            // 分享新需求
            async function twoShare () {
                if (that.shareBody) {
                    readyData = {
                        title: shareTitle, // 分享标题
                        link: link, // 分享链接
                        imgUrl: sharePhoto, // 分享图标
                        desc: shareSummary, // 分享描述
                    }
                } else {
                    readyData = {
                        title: that.wxData && that.wxData.title ? that.wxData.title : '您的好友邀请您一起参加活动', // 分享标题
                        link: that.wxData && that.wxData.link ? that.wxData.link : link, // 分享链接
                        imgUrl: that.wxData && that.wxData.photo ? that.wxData.photo : that.staticImageUrl('images/home/haokanhaowan_logo.png'), // 分享图标
                        desc: that.wxData && that.wxData.content ? that.wxData.content : '您的好友邀请您一起参加活动', // 分享描述
                    }
                }
                let share = localStorage.getItem('share') ? JSON.parse(localStorage.getItem('share')) : null
                if (that.$route.fullPath.indexOf('linkId') > -1 && ((share == null) || (share.linkId != that.$route.query.linkId))) {
                    if (that.userId != 0) {
                        let params = {
                            linkId: that.$route.query.linkId,
                            userId: that.userId,
                            thirdId: that.thirdId
                        }
                        await that.$store.dispatch('getByLinkIdApi', params).then((data) => {
                            if (data.success) {
                                let res = data.result
                                readyData.link = StringUtils.delUrlParams(readyData.link, 'linkId') + `&nodeId=${res.nodeId}`
                                localStorage.setItem('share', JSON.stringify(res))
                            }
                        })

                    }
                } else if (that.$route.fullPath.indexOf('linkId') > -1 && share && (share.linkId == that.$route.query.linkId)) {
                    readyData.link = StringUtils.delUrlParams(readyData.link, 'linkId') + `&nodeId=${share.nodeId}`
                }
                if (that.$route.fullPath.indexOf('nodeId') > -1) {
                    let nodeId = that.$route.query.nodeId
                    if (share && (nodeId == share.nodeId)) {
                        readyData.link = readyData.link + `&nodeId=${nodeId}`
                    } else if (share && (nodeId == share.parentNodeId)) {
                        readyData.link = readyData.link + `&nodeId=${share.nodeId}`
                    } else {
                        let params = {
                            nodeId: nodeId,
                            userId: that.userId,
                            thirdId: that.thirdId
                        }
                        await that.$store.dispatch('getByNodeIdApi', params).then((data) => {
                            if (data.success) {
                                let res = data.result;
                                readyData.link = readyData.link + `&nodeId=${res.nodeId}`
                                localStorage.setItem('share', JSON.stringify(res))
                            }
                        })
                    }
                }
            }
            let wxConfig = await XWxConfig.getConfig();
            if (wxConfig) {
                twoShare()
                wx.config(wxConfig);
                wx.ready(() => {
                    //分享给朋友
                    if (!!wx.updateAppMessageShareData) {
                        wx.updateAppMessageShareData({
                            title: readyData && readyData.title ? readyData.title : "updateAppMessageShareData测试标题", // 分享标题
                            link: readyData && readyData.link ? readyData.link : window.location.href, // 分享链接
                            imgUrl: readyData && readyData.imgUrl ? readyData.imgUrl : that.staticImageUrl('images/home/haokanhaowan_logo.png'), // 分享图标
                            desc: readyData && readyData.desc ? readyData.desc : "updateAppMessageShareData测试内容", // 分享描述
                            success: function () {
                                if ((that.$route.fullPath.indexOf('store') != -1) || (that.$route.fullPath.indexOf('activity') != -1)) {
                                    params.sendShareMsg = true;
                                    that.$store.commit('getWxUserInfo', params)
                                }
                                that.$emit('wxShareCb', params);
                            },
                            trigger () {
                                // 修改分享平台
                                // ts.pgShare.config.channel = 2;  分享到QQ时
                                ts.pgShare.config.url = readyData.link;
                                // 记录分享操作
                                ts.pgShare.call();
                                // 更改分享链接，设置分享ID
                                that.link = ts.pgShare.changeUrl(readyData.link);
                            }
                        });
                    } else {
                        wx.onMenuShareAppMessage({
                            title: readyData && readyData.title ? readyData.title : "onMenuShareAppMessage测试标题", // 分享标题
                            link: readyData && readyData.link ? readyData.link : window.location.href, // 分享链接
                            imgUrl: readyData && readyData.imgUrl ? readyData.imgUrl : that.staticImageUrl('images/home/haokanhaowan_logo.png'), // 分享图标
                            desc: readyData && readyData.desc ? readyData.desc : "onMenuShareAppMessage测试内容", // 分享描述
                            success: function () {
                                if ((that.$route.fullPath.indexOf('store') != -1) || (that.$route.fullPath.indexOf('activity') != -1)) {
                                    params.sendShareMsg = true;
                                    that.$store.commit('getWxUserInfo', params)
                                }
                                that.$emit('wxShareCb', params);
                            },
                            trigger () {
                                // 修改分享平台
                                // ts.pgShare.config.channel = 2;  分享到QQ时
                                ts.pgShare.config.url = readyData.link;
                                // 记录分享操作
                                ts.pgShare.call();
                                // 更改分享链接，设置分享ID
                                that.link = ts.pgShare.changeUrl(readyData.link);
                            }
                        })
                    }
                    //分享到朋友圈
                    if (!!wx.updateTimelineShareData) {
                        wx.updateTimelineShareData({
                            title: readyData && readyData.title ? readyData.title : "updateTimelineShareData测试标题", // 分享标题
                            link: readyData && readyData.link ? readyData.link : window.location.href, // 分享链接
                            imgUrl: readyData && readyData.imgUrl ? readyData.imgUrl : that.staticImageUrl('images/home/haokanhaowan_logo.png'), // 分享图标
                            success: function () {
                                if ((that.$route.fullPath.indexOf('store') != -1) || (that.$route.fullPath.indexOf('activity') != -1)) {
                                    params.sendShareMsg = true;
                                    that.$store.commit('getWxUserInfo', params)
                                }
                                that.$emit('wxShareCb', params);
                            },
                            fail(data){
                                console.log('failData',data)
                            },
                            trigger () {
                                ts.pgShare.config.url = readyData.link;
                                // 记录分享操作
                                ts.pgShare.call();
                                // 更改分享链接，设置分享ID
                                that.link = ts.pgShare.changeUrl(readyData.link);
                            }
                        });
                    } else {
                        wx.onMenuShareTimeline({
                            title: readyData && readyData.title ? readyData.title : "onMenuShareTimeline测试标题", // 分享标题
                            link: readyData && readyData.link ? readyData.link : window.location.href, // 分享链接
                            imgUrl: readyData && readyData.imgUrl ? readyData.imgUrl : that.staticImageUrl('images/home/haokanhaowan_logo.png'), // 分享图标
                            success: function () {
                                if ((that.$route.fullPath.indexOf('store') != -1) || (that.$route.fullPath.indexOf('activity') != -1)) {
                                    params.sendShareMsg = true;
                                    that.$store.commit('getWxUserInfo', params)
                                }
                                that.$emit('wxShareCb', params);
                            },
                            trigger () {
                                ts.pgShare.config.url = readyData.link;
                                // 记录分享操作
                                ts.pgShare.call();
                                // 更改分享链接，设置分享ID
                                that.link = ts.pgShare.changeUrl(readyData.link);
                            }
                        })
                    }


                    wx.checkJsApi({
                        jsApiList: wxConfig.jsApiList, // 需要检测的JS接口列表，所有JS接口列表见附录2,
                        success: function (res) {
                            // 以键值对的形式返回，可用的api值true，不可用为false
                            // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
                            // alert("check js api -- " + JSON.stringify(res))
                        }
                    });
                });
                wx.error(function (res) {
                    console.log(res, "wx验证失败！")
                });
            }
        },
    },
    watch: {},
    /*swiperContent.list[swiperIndex]*/
    components: {
        'wx_share_pub_qrcode': () => import('./WxSharePubQrcode'),
        'wx-show-menu': () => import('./WxShowMenu'),
    }
}

</script>
<style scoped>
</style>
